#include "git-commit.h"

#include <cassert>
#include <git2/commit.h>

namespace git
{

Commit::Commit(git_commit *commit)
    : commit_(commit) {
}

Commit::Commit(Commit &&b)
    : commit_(b.commit_) {
    b.commit_ = nullptr;
}

Commit::~Commit() {
    if (commit_) {
        git_commit_free(commit_);
        commit_ = nullptr;
    }
}

Commit &Commit::operator=(Commit &&b) {
    if (this != &b && commit_ != b.commit_) {
        if (commit_) {
            git_commit_free(commit_);
        }
        commit_ = b.commit_;
        b.commit_ = nullptr;
    }
    return *this;
}

bool Commit::operator==(const Commit &b) const {
    if (commit_ && b.commit_) {
        const git_oid *idA = git_commit_id(commit_);
        const git_oid *idB = git_commit_id(b.commit_);
        if (idA && idB) {
            return git_oid_equal(idA, idB);
        } else {
            if (!idA && !idB) {
                return true;
            } else {
                return false;
            }
        }
    } else {
        if (!commit_ && !b.commit_) {
            return true;
        } else {
            return false;
        }
    }
}

std::string Commit::oidHex() const {
    assert(commit_);
    const git_oid *id = git_commit_id(commit_);
    char buffer[GIT_OID_HEXSZ + 1] = {};
    if (0 == git_oid_fmt(buffer, id)) {
        return std::string(buffer, GIT_OID_HEXSZ);
    } else {
        return std::string();
    }
}

} // namespace git
